import os
import uuid

from dotenv import load_dotenv
from elevenlabs import VoiceSettings
from elevenlabs.client import ElevenLabs

load_dotenv()

ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")

if not ELEVENLABS_API_KEY:
    raise ValueError("ELEVENLABS_API_KEY environment variable not set")

client = ElevenLabs(
    api_key=ELEVENLABS_API_KEY,
)


def text_to_speech_file(text: str) -> str:
    """
    Converts text to speech and saves the output as an MP3 file.

    This function uses a specific client for text-to-speech conversion. It configures
    various parameters for the voice output and saves the resulting audio stream to an
    MP3 file with a unique name.

    Args:
        text (str): The text content to convert to speech.

    Returns:
        str: The file path where the audio file has been saved.
    """
    # Calling the text_to_speech conversion API with detailed parameters
    response = client.text_to_speech.convert(
        voice_id="pNInz6obpgDQGcFmaJgB",  # Adam pre-made voice
        # voice_id="flHkNRp1BlvT73UL6gyz", #aniamation style
        # voice_id="nPczCjzI2devNBz1zQrb",  # Brian
        optimize_streaming_latency="0",
        output_format="mp3_22050_32",
        text=text,
        model_id="eleven_turbo_v2",
        # use the turbo model for low latency, for other languages use the `eleven_multilingual_v2`
        voice_settings=VoiceSettings(
            stability=0.8,
            similarity_boost=1.0,
            style=0.0,
            use_speaker_boost=True,
        ),
    )

    # 生成唯一的文件名并设置保存路径
    file_name = f"{text[:15].replace(' ', '-')}.mp3"
    save_file_path = os.path.join(
        os.path.dirname(
            os.path.dirname(__file__)),
        'static',
        'audio',
        file_name)

    # 确保目标目录存在
    os.makedirs(os.path.dirname(save_file_path), exist_ok=True)

    # 写入音频流到文件
    with open(save_file_path, "wb") as f:
        for chunk in response:
            if chunk:
                f.write(chunk)

    print(f"新的音频文件已成功保存到 {save_file_path}")

    # 返回保存的音频文件路径
    return save_file_path


if __name__ == "__main__":
    text_to_speech_file("spill")
